package com.yc.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.yc.mapper.SubscriptionMessageMapper;
import com.yc.service.SubscriptionMessageService;
import com.yc.vo.SubscriptionMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 公众号消息订阅业务类实现类
 * @version 1.0
 * @Date 2023/12/24 20:59
 */
@Service
public class SubscriptionMessageServiceImpl implements SubscriptionMessageService {


    @Resource
    private SubscriptionMessageMapper subscriptionMessageMapper;

    /**
     * 发送封装完成的订阅消息
     * @return
     */
    @Override
    public List<SubscriptionMessage> sendMessage() {
       return   subscriptionMessageMapper.selectMessageInfo();
    }


    /**
     * 获取accessToken 用于构建模板消息发送的url入参  此token有效期只有2小时 要存redis?
     * @throws Exception
     *
     */
    public String getAccessToken(String appId,String appSecret) throws Exception{
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId +"&secret=" + appSecret;
        String res = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String accessToken = jsonObject.getString("access_token");  // key : expires_in 为过期时间  为7200s 后续如果需要缓存 可能要用到
        System.out.println("accessToken:"+accessToken);
        return accessToken;
    }


}
